package stool.juc.readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Felix
 * @Description
 * @Date 2023-02-19
 */
public class ReadWriteLockUsed {
    public static void main(String[] args) {
        MyCacheImp myCache = new MyCacheImp();
        // write
        for (int i = 0; i < 5; i++) {
            final int key = i;
            new Thread(() -> {
                myCache.put(key + "", key + "");
            }, String.valueOf(i)).start();
        }
        // read
        for (int i = 0; i < 5; i++) {
            final int key = i;
            new Thread(() -> {
                myCache.get(key + "");
            }, String.valueOf(i)).start();
        }
    }

}

class MyCacheImp {

    private volatile Map<String, Object> map = new HashMap<>();
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public void put(String key, Object value) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入数据key" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入完成key" + key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void get(String key) {
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读取数据key" + key);
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读取数据key" + key);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }
}